<!-- ServerSentEvent -->
<template>
<v-card>
    <v-card-title>EventSource</v-card-title>
    <v-card-subtitle>
      <p>组件：a polyfill for http://www.w3.org/TR/eventsource/</p>
      <p>官网：<a href="https://github.com/Yaffle/EventSource/">https://github.com/Yaffle/EventSource/</a> </p>
    </v-card-subtitle>
     <v-card-text>
      <v-container>
        <v-row>
          <v-col cols="12">
            <v-btn @click="openSSE">打开</v-btn>
            <v-btn @click="closeSSE">关闭</v-btn>
          </v-col>
          <v-col  cols="12">
            url: {{url}}
          </v-col>
          <v-col  cols="12">
            readyState: {{readyState}}
          </v-col>
        </v-row>
        <v-row>
          <div>msg: {{msg}}</div>
        </v-row>
      </v-container>
    </v-card-text>
    <v-card-actions></v-card-actions>
  </v-card>
</template>
<script>
export default {
  name: 'ServerSentEvent',
  components: {},
  data: function () {
    return {
      msg: '',
      url: 'http://fortuna-dev-server/admin/serversendevent/notic',
      source: null
    }
  },
  mounted: function () {},
  computed: {
    readyState: function() {
      if (this.source instanceof EventSource) {
        return this.source.readyState
      } else {
        return null
      }
    }
  },
  methods: {
    openSSE: function() {
      this.source = new EventSource(this.url)
      const _that = this
      // 消息事件
      this.source.onmessage = function(event) {
        // console.log('消息事件')
        // console.log(event)
        _that.msg = event.data
      }
      // 连接打开事件
      this.source.onopen = function(event) {
        // console.log('连接成功！')
      }
      // 错误事件
      this.source.onerror = function(event) {
        // console.log('错误事件')
        // console.log(event)
      }
      // 自定义事件
      this.source.addEventListener('myEvent', function(event) {
        // console.log('自定义事件')
        // console.log(event)
      })
    },
    closeSSE: function() {
      if (this.source instanceof EventSource) {
        this.source.close()
        this.source = null
      }
    }
  }
}
</script>
<style scoped>
</style>
